package com.founder.gateway.component.transport.netty.extension.support;

import static com.founder.gateway.system.util.HttpNormUtil.APPEND_UTF_8;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.setu.framework.search.SetuGridSearchUtil;
import org.setu.framework.thread.SetuThreadLocalHandler;
import org.setu.framework.util.SetuApplicationUtil;
import org.setu.orm.automatic.service.SetuAutomaticService;

import com.founder.gateway.component.transport.netty.exception.NettyException;
import com.founder.gateway.component.transport.netty.filter.NettyFilterChain;
import com.founder.gateway.component.transport.netty.http.NettyHttpRequest;
import com.founder.gateway.component.transport.netty.http.NettyHttpResponse;
import com.founder.gateway.orm.fzapi.bean.entity.ApiEntityEntity;
import com.founder.gateway.system.bean.SetuResult;
import com.founder.gateway.system.consts.ApiSetuErrorCode;
import com.founder.gateway.system.consts.Consts;

import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;

public class AutoMaticEntityNettyHttpFilter extends AbstractNettyHttpFilter {

    @Override
    public void doFilter(NettyHttpRequest request, NettyHttpResponse response, NettyFilterChain chain)
            throws IOException, NettyException {
        ApiEntityEntity entity = chain.getApiEntityEntity();
        if (entity.transfer().getAutomaticEntity()) {
            Map<String, String> PARAM_MAP = SetuThreadLocalHandler.PARAM_MAP.get();
            Map<String, List<String>> map = request.getParameterMap().getMaps();
            for (String key : map.keySet()) {
                PARAM_MAP.put(key, map.get(key).get(0));
            }
            String[] str = entity.getUrl().split(",");
            try {
                if (response.headers().get(HttpHeaderNames.CONTENT_TYPE) == null) {
                    response.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON + APPEND_UTF_8);
                }
                Object obj = SetuApplicationUtil.getBean(SetuAutomaticService.class).execute(str[0], str[1]);
                if (obj != null && obj instanceof byte[]) {
                    response.setContent((byte[]) obj);
                } else {
                    SetuResult result = new SetuResult();
                    Object total = SetuThreadLocalHandler.getParam(SetuGridSearchUtil.TOTAL);
                    if (total != null) {
                        result.setTotal(Integer.valueOf(total.toString()));
                    }
                    result.setCode(Consts.RESULT_CODE_SUCCESS);
                    result.setRows(obj);
                    response.setSetuResult(result);
                }
            } catch (Throwable e) {
                throw new NettyException(ApiSetuErrorCode.API_AUTOMATIC_ERROR, e.getMessage());
            }
        } else {
            chain.doFilter(request, response);
        }
    }
}
